package com.csw.mysqldate.interceptor.traceId;

import com.alibaba.fastjson.JSON;
import com.csw.mysqldate.result.Result;
import com.csw.mysqldate.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class MarkInterceptor {
    static String package_name = "com.csw.";

    //要扫描的方法必须是public
    @Around("execution(* com.csw..*Controller.*(..))")
    public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();

        Object[] args = joinPoint.getArgs();
        //主方法从Attribute里拿，从方法从Header拿
        String requestId = TraceIdFilter.getRequestId();

        log.info("请求路径：{}，【开始】", request.getServletPath());
        if (args != null) {
            for (Object arg : args) {
                if (isCustrom(arg)) {
                    log.info("请求路径：{}，【入参】：{}", request.getServletPath(), JSON.toJSONString(arg));
                }
            }
        }
        long begin = System.nanoTime();
        Object result = joinPoint.proceed(args);
        long end = System.nanoTime();
        log.info("请求路径：{}，【耗时】：{}毫秒", request.getServletPath(), (end - begin) / 1000000);
        if (result instanceof Result) {
            ((Result<?>) result).setRequestId(requestId);
        }
        if (isCustrom(result)) {
            log.info("；请求路径：{}，【出参】：{}", request.getServletPath(), JSON.toJSONString(result));
        }
        log.info("请求路径：{}，【结束】", request.getServletPath());
        return result;
    }

    //要扫描的方法必须是public
    @Around("execution(* com.csw..GlobalExceptionHandler.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        Object object = pjp.proceed();

        String requestId = TraceIdFilter.getRequestId();
        if (requestId == null) {
            requestId = "未进入方法报错";
        }

        if (object instanceof Result) {//Result是返回的封装对象，具体可以看我其他博客，里面多一个参数requestId
            ((Result<?>) object).setRequestId(requestId);
        }
        log.info("请求路径：{}，【结束】", request.getServletPath());
        return object;
    }

    private static boolean isCustrom(Object arg) {
        if (arg == null) {
            return false;
        }
        String path = arg.getClass().getName();
        //其他的可以自己补充
        if (path.startsWith(package_name)) {
            return true;
        } else if (path.startsWith("java.lang.String") ||
                path.startsWith("java.lang.Integer") ||
                path.startsWith("java.lang.Long") ||
                path.startsWith("java.util.List") ||
                path.startsWith("java.util.ArrayList") ||
                path.startsWith("java.util.Map")) {
            return true;
        } else if (path.startsWith("com.alibaba.fastjson.JSONObject") ||
                path.startsWith("com.google.gson.Gson")) {//json对象
            return true;
        }

        if (path.startsWith("java.io.")) {
            return false;
        }

        return false;
    }


    /**
     * 声明环绕通知
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    //要扫描的方法必须是public
    @Around("execution(* com.csw..*Dao.*(..))||execution(* com.csw..*Mapper.*(..))")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        //主方法从Attribute里拿，从方法从Header拿
        String requestId = TraceIdFilter.getRequestId();
        long begin = System.nanoTime();
        Object obj = pjp.proceed();
        long end = System.nanoTime();

        log.info("请求路径：{}，调用Mapper方法：{}，参数：{}，执行耗时：{}纳秒，耗时：{}毫秒", request.getServletPath(), pjp.getSignature().toString(), Arrays.toString(pjp.getArgs()),
                (end - begin), (end - begin) / 1000000);
        return obj;
    }
}
